<?php

/*
	PIE Content Management System
	John Girata
	Licensed under the GNU General Public License version 3
*/

defined('PIESECVAR') or die('Restricted Access');

class com_login
{
	function __construct()
	{
		if(empty($_POST['login_attempt']))
			$this->load_form() ;
		else 
			$this->check_login_info();
	}
	
	// Check the login data in $_POST against that in the database
	private function check_login_info()
	{
		global $login, $db;
		
		$username = $db->escape($_POST['username']);
		$password = $_POST['password'];
		
		if(!$login->check_login($username, $login->db_encrypt($password)))
		{
			if($db->get_num_rows() == 0)
				$this->load_form('Error: Invalid username/password combination.');
			else
				$controller->report_error("Multiple usernames in database; username = $username");
		}
		else
		{
			setCookie('username', $username);
			setCookie('password', $login->cookie_encrypt($password));
		}
	}
	
	private function load_form($error_msg = '')
	{
		global $controller;
		
		$form = file_get_contents(TMPL_DIR . 'com_login/login_form.tmpl');
		$replacement = '';
		
		if(!empty($error_msg))
			$replacement = '<span class="error">' . $error_msg . '</span>';
		
		$form = preg_replace('/<%%ERROR%%>/', $replacement, $form);
		
		$controller->add_content($form);
		$controller->set_title('Login');
	}
}

$com_login = new com_login();

?>